package com.ld.hpfs.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.pojo.CustomerContact;
import com.ld.hpfs.pojo.ExtPager;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.service.DealService;
import com.ld.hpfs.service.ExpressPrintService;
import com.ld.hpfs.service.ReportService;
import com.ld.hpfs.web.interseptor.WebConstants;
import com.ld.hpfs.web.controller.DealController;

@Controller
public class ExpressPrintController {
	private static final Logger logger = LoggerFactory.getLogger(ExpressPrintController.class);

	@Autowired
	private ExpressPrintService expressPrintService;
	@Autowired
	private DealService dealService;
	@Autowired
	private DealController dealcontroller;
	//导出快递单
	@Autowired
    private ReportService      reportService;
	/**
	 * 获取快递单打印信息
	 * @param page
	 * @param session
	 * @param request
	 * @param response
	 * @param writer
	 */
    @RequestMapping(value = "/getExpressPrintList")
    @ResponseBody
    public void getExpressPrintList(
    		ExtPager page,
    		HttpSession session,
    		HttpServletRequest request,
            HttpServletResponse response,
            PrintWriter writer){
    	HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				
				param.put("pageEnd", page.getStart() + page.getLimit());
				param.put("pageStart", page.getStart()+1);
				param.put("express", request.getParameter("express"));
		        param.put("lang",session.getAttribute(WebConstants.CURRENT_LANG).toString());
		        param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
		       
		       
				/* 单据状态 */
				String state2 = request.getParameter("state2") == null ? null
						: (String) request.getParameter("state2");

				/* 发票状态 */
				String state3 = request.getParameter("state3") == null ? null
						: (String) request.getParameter("state3");
		        
		        String str = request.getParameter("str") == null ? null
						: (String) request.getParameter("str");
		        /* 日期 */
				String DateFirst = request.getParameter("startday") == "" ? null
						: (String) request.getParameter("startday");
				String DateEnd = request.getParameter("endday") == "" ? null
						: (String) request.getParameter("endday");
				/* 得到一个或多个单据号 */
				String DOCUMENT_NO = request.getParameter("nos") == "" ? null
						: (String) request.getParameter("nos");
				/* 对单据号进行判断不为空的话放入集合之中 */
				if (DOCUMENT_NO != null && DOCUMENT_NO != "") {
					List<HashMap<String, String>> lists = new ArrayList<HashMap<String, String>>();
					String[] nos = DOCUMENT_NO.split(",");
					HashMap<String, String> map = new HashMap<String, String>();
					for (int i = 0; i < nos.length; i++) {
						map = new HashMap<String, String>();
						map.put("nos", nos[i]);
						lists.add(map);
					}
					param.put("DOCUMENT_NO", lists);
				} else {
					param.put("DOCUMENT_NO", null);
				}
				/* 单据号的开始和结束范围 */
				String DOCUMENT_NO_First = request
						.getParameter("startno") == "" ? null
						: (String) request.getParameter("startno");
				String DOCUMENT_NO_End = request.getParameter("endno") == "" ? null
						: (String) request.getParameter("endno");
				/* 付款单位 */
				String custname = request.getParameter("custom") == "" ? null
						: (String) request.getParameter("custom");
				/* 快递类型 */
				String type = request.getParameter("type") == "" ? null
						: (String) request.getParameter("type");
				/* 快递单号 */
				String sexpressno = request.getParameter("sexpressno") == "" ? null
						: (String) request.getParameter("sexpressno");
				String eexpressno = request.getParameter("eexpressno") == "" ? null
						: (String) request.getParameter("eexpressno");
				param.put("DOCUMENT_NO_First", DOCUMENT_NO_First);
				param.put("DOCUMENT_NO_End", DOCUMENT_NO_End);
				param.put("DateFirst",
						DateFirst == null ? null : DateFirst.substring(0, 10));
				param.put("DateEnd",
						DateEnd == null ? null : DateEnd.substring(0, 10));
				param.put("custname", custname);
				param.put("type", type);
				param.put("sexpressno", sexpressno);
				param.put("eexpressno", eexpressno);
				param.put("str", str);
				param.put("state2", state2);
				param.put("state3", state3);
		        
		        ArrayList<HashMap<String, Object>> logs = expressPrintService.getExpressPrintList(param);
				if (logs != null && logs.size() > 0) {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", logs);
				} else {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", "");
				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
    }

//    /**
//     * 格式化快递单打印数据
//     * @param expressPrints
//     * @param count
//     * @return
//     */
//    private String formatExpressPrintResults(List<ExpressPrint> expressPrints, int count){
//    	
//        StringBuffer sb = new StringBuffer();
//        sb.append("{");
//        sb.append("\r\n");
//        sb.append("\"success\": true,");
//        sb.append("\r\n");
//        sb.append("\"total\":").append(count).append(",");
//        sb.append("\r\n");
//        sb.append("\"children\": [");
//        sb.append("\r\n");
//        if (expressPrints != null){
//            for (int i = 0; i < expressPrints.size(); i++){
//            	ExpressPrint expressPrint = expressPrints.get(i);
//                int id = expressPrint.getId();
//                String express = expressPrint.getExpress();
//                String document_no = expressPrint.getDocument_no();
//                String document_date = expressPrint.getDocument_date();
//                int cust_id = expressPrint.getCust_id();
//                String customer = expressPrint.getCustomer();
//                String receiver = expressPrint.getReceiver();
//                String amount = expressPrint.getAmount();
//                String tax_amount = expressPrint.getTax_amount();
//                String status = expressPrint.getStatus();
//                String remark = expressPrint.getRemark();
//                String invoice_no = expressPrint.getInvoice_no();
//                String invoice_date = expressPrint.getInvoice_date();
//                String department = expressPrint.getDepartment();
//                
//                
//                sb.append("{\"id\":\"").append(id).append("\",")
//                        .append("\"express\":\"").append(express).append("\",")
//                        .append("\"document_no\":\"").append(document_no).append("\",")
//                        .append("\"document_date\":\"").append(document_date).append("\",")
//                        .append("\"cust_id\":\"").append(cust_id).append("\",")
//                        .append("\"customer\":\"").append(customer).append("\",")
//                        .append("\"receiver\":\"").append(receiver).append("\",")
//                        .append("\"amount\":\"").append(amount).append("\",")
//                        .append("\"tax_amount\":\"").append(tax_amount).append("\",")
//                        .append("\"status\":\"").append(status).append("\",")
//                        .append("\"invoice_no\":\"").append(invoice_no).append("\",")
//                        .append("\"invoice_date\":\"").append(invoice_date).append("\",")
//                        .append("\"department\":\"").append(department).append("\",")
//                        .append("\"remark\":\"").append(remark).append("\"").append("}");
//
//                if (i < expressPrints.size() - 1){
//                    sb.append(",");
//                }
//                sb.append("\r\n");
//            }
//        }
//        sb.append("]");
//        sb.append("\r\n");
//        sb.append("}");
//
//        try{
//            return sb.toString();
//        }
//        catch (Exception e){
//            e.printStackTrace();
//        }
//
//        return "";
//    }
    
    /**
	 * 获取快递单收件人信息
	 * @param page
	 * @param session
	 * @param request
	 * @param response
	 * @param writer
	 */
    @RequestMapping(value = "/getContactList")
    @ResponseBody
    public void getContactList(
    		ExtPager page,
    		HttpSession session,
    		HttpServletRequest request,
            HttpServletResponse response,
            PrintWriter writer){
    	
        Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
        if (currentCompany == null){
            return;
        }

        HashMap<String, Object> param = new HashMap<String, Object>();
        param.put("cust_id", request.getParameter("cust_id"));
        List<CustomerContact> contacts = expressPrintService.getContactList(param);
        
        response.setContentType("text/plain;charset=UTF-8");
        String resultstring = formatContactResults(contacts);
        logger.debug("{}", resultstring);
        writer.print(resultstring);
    }

    /**
     * 格式化快递单收件人数据
     * @param contacts
     * @return
     */
    private String formatContactResults(List<CustomerContact> contacts){
    	
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        sb.append("\r\n");
        sb.append("\"success\": true,");
        //sb.append("\r\n");
        //sb.append("\"total\":").append(count).append(",");
        sb.append("\r\n");
        sb.append("\"children\": [");
        sb.append("\r\n");
        if (contacts != null){
            for (int i = 0; i < contacts.size(); i++){
            	CustomerContact contact = contacts.get(i);

            	int contact_id = contact.getContact_id();
            	int cust_id = contact.getCust_id();
            	int group_id = contact.getGroup_id();
            	String contact_company_name = contact.getContact_company_name();
            	String contact_name = contact.getContact_name();
            	String contact_address = contact.getContact_address();
            	String contact_tel = contact.getContact_tel();
            	String contact_city = contact.getContact_city();
            	String remark = contact.getRemark();
            	String ref01 = contact.getRef01();
            	String ref02 = contact.getRef02();
            	String ref03 = contact.getRef03();
            	String ref04 = contact.getRef04();
            	String ref05 = contact.getRef05();
            	int update_id = contact.getUpdate_id();
            	String update_name = contact.getUpdate_name();
            	String update_time = contact.getUpdate_time();
            	String contact_email = contact.getContact_email();
            	String phone_number = contact.getPhone_number();
                
                sb.append("{\"contact_id\":\"").append(contact_id).append("\",")
                        .append("\"cust_id\":\"").append(cust_id).append("\",")
                        .append("\"group_id\":\"").append(group_id).append("\",")
                        .append("\"contact_company_name\":\"").append(contact_company_name).append("\",")
                        .append("\"contact_name\":\"").append(contact_name).append("\",")
                        .append("\"contact_address\":\"").append(contact_address).append("\",")
                        .append("\"contact_tel\":\"").append(contact_tel).append("\",")
                        .append("\"contact_city\":\"").append(contact_city).append("\",")
                        .append("\"remark\":\"").append(remark).append("\",")
                        .append("\"ref01\":\"").append(ref01).append("\",")
                        .append("\"ref02\":\"").append(ref02).append("\",")
                        .append("\"ref03\":\"").append(ref03).append("\",")
                        .append("\"ref04\":\"").append(ref04).append("\",")
                        .append("\"ref05\":\"").append(ref05).append("\",")
                        .append("\"update_id\":\"").append(update_id).append("\",")
                        .append("\"update_name\":\"").append(update_name).append("\",")
                        .append("\"update_time\":\"").append(update_time).append("\",")
                        .append("\"contact_email\":\"").append(contact_email).append("\",")
                        .append("\"phone_number\":\"").append(phone_number).append("\"").append("}");

                if (i < contacts.size() - 1){
                    sb.append(",");
                }
                sb.append("\r\n");
            }
        }
        sb.append("]");
        sb.append("\r\n");
        sb.append("}");

        try{
            return sb.toString();
        }
        catch (Exception e){
            e.printStackTrace();
        }

        return "";
    }
    
    /**
     * 更新快递单快递公司信息
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateExpress", method = RequestMethod.POST)
	public void updateExpress(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		
		String id = request.getParameter("id");
		String express = request.getParameter("express");
		String contact_id = request.getParameter("contact_id");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param.put("id", id);
		        param.put("express", express);
		        param.put("contact_id", contact_id);
		        try {
		        	expressPrintService.updateExpress(param);
		        	result.put("resultcode", 0);
		        } catch (Exception e) {
		        	logger.debug(e.getMessage());
		        	result.put("resultcode", 9);
		        }
			} else {
				result.put("resultcode", 9);
			}
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
    
    /**
     * 打印快递单
     * @param session
     * @param request
     * @return
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    @RequestMapping(value = "/printExpress")
    @ResponseBody
    public void printExpress(
    		HttpSession session,
    		HttpServletRequest request,
    		HttpServletResponse response,
    		PrintWriter writer) throws ClientProtocolException, IOException{
    	try{
    		User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
    		String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
    		String ids = request.getParameter("ids");
    		//获取参数中快递公司id
    		String express = request.getParameter("express");
    		//获取参数中起始快递单号
    		String expressStartNoStr = request.getParameter("expressStartNo");
    		// 获取快递公司对应的临时表
    		HashMap<String, Object> tableNameParam = new HashMap<String, Object>();
    		tableNameParam.put("express_id", express);
    		
    		String table = expressPrintService.getExpressPrintTableName(tableNameParam);
    		//导出水晶报表
    		String report_name = "快递单";
    		String report_param = "report_name=" + table.substring(8);
    		String detail = "起始快递号:" + expressStartNoStr;
    		HashMap<String,Object> paramPDF = new HashMap<String,Object>();
    		response.setContentType("text/plain;charset=UTF-8");
    		
    		paramPDF.put("report_name",report_name );
    		paramPDF.put("report_param",report_param + ";user_id=" + user.getUserId());
    		paramPDF.put("creator_id", user.getUserId());
    		paramPDF.put("companyId", companyId);		
    		paramPDF.put("detail", detail);
    		int check = reportService.insertReportTaskGridList(paramPDF);   //插入任务
    		expressPrintService.printExpress(session, request, response, writer,check);
    		
    		// 调用快递100接口 -----
    		HashMap<String, Object> param = new HashMap<String, Object>();
    		// 检查当前公司是否启用快递100功能
			int expressStatus = dealService.getExpressStatus(companyId);
			if (expressStatus == 1) {
				String[] id = ids.split("\\|");
				for (int i = 0; i < id.length; i++) {
					param.put("id", id[i]);
					// 快递单扫描页面当单据有了快递单号时发送快递状态请求
					try {
						HashMap<String, Object> document = new HashMap<String, Object>();
						document = dealService.getDataForExpress(param);
						// 快递公司调用方法
						dealcontroller.doExpressImpl(document);
					} catch (Exception e) {
						System.out.println(e);
					}
				}
			}
			// end -----
    	}
    	catch(Exception e){
    		writer.print("{\"resultcode\":\"-1\"}");
    	}
    	finally{
    		writer.flush();
			writer.close();
    	}
    }
    
    // 获取联系人信息
    @RequestMapping(value = "/getContacts")
	public void getcontact(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		
		String cust_id = request.getParameter("cust_id");
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			param.put("cust_id", cust_id);
			ArrayList<HashMap<String, Object>> result = expressPrintService.getContacts(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
}
